<?php
namespace  App\Services;


class RequestService
{

    protected $header;  //http header init
    public function __construct()
    {
        $ip = getIp();
        $this->header = [];
        $this->header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
        $this->header[] = 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8';
        $this->header[] = 'Cache-Control: max-age=0';
        $this->header[] = 'Connection: keep-alive';
        $this->header[] = 'Cookie: UM_distinctid=16be41a5eab97-01488dfb55f119-31353143-4fa2e-16be41a5eae1b7';
        $this->header[] = 'Referer: http://www.mzhu8.com/book/106/index.html';

 //       $this->header[] = 'Host: www.zsymcm.com';
        $this->header[] = 'If-None-Match: 1551063493|';
        $this->header[] = 'Upgrade-Insecure-Requests: 1';
//        $this->header[] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36';
        $this->header[] = 'User-Agent: Mozilla/5.0 (Linux; Android 8.1.0; Bigmi 9 Pro Build/OPM1.171019.019; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044705 Mobile Safari/537.36 MMWEBID/4317 MicroMessenger/7.0.4.1420(0x2700043C) Process/tools NetType/WIFI Language/zh_CN';
        $this->header[] = 'CLIENT-IP: '.$ip;
        $this->header[] = 'X-FORWARDED-FOR: '.$ip;
    }

    public function getContent($url)
    {
        return file_get_contents($url);
    }

    public function send($url, $type = 'GET', $params = false, $encoding = 'GBK')
    {

		$host = parse_url($url)['host'];
		$this->header[] = 'Host: '.$host;
//		dd($this->header);
		//$this->header[] = 'Referer: https://t.bilibili.com/h5/dynamic/detail/27405946?tab=1&type=2';


        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//	    curl_setopt($ch, CURLOPT_ENCODING,'gzip');
        if ($type == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            $params && curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        $html = curl_exec($ch);

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($html === false) {
            resolve('log')->error("链接: {$url}, curl失败，error: " . curl_errno($ch) . "请注意查看");
            return false;
        }
        if ($httpCode !== 200) {
            resolve('log')->error("链接: {$url}, curl code不等于200，code: " . curl_errno($ch) . "请注意查看");
            return false;
        }
        curl_close($ch);
        return ($encoding != 'utf-8') ? mb_convert_encoding($html, 'UTF-8', $encoding) : $html;
    }




    public function setHeader($key,$value)
    {
        $this->header[$key] = $value;
    }




}
